package net.xdclass.online_xdclass.service.Impl;

import net.xdclass.online_xdclass.cofing.CacheKeyManager;
import net.xdclass.online_xdclass.model.entity.Video;
import net.xdclass.online_xdclass.model.entity.VideoBanner;
import net.xdclass.online_xdclass.mapper.VideoMapper;
import net.xdclass.online_xdclass.service.VideoService;
import net.xdclass.online_xdclass.utils.BaseCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author kingtao
 * @date 2022/3/3
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Resource
    private VideoMapper videoMapper;

    @Autowired
    private BaseCache baseCache;

    @Override
    public List<Video> listVideo() {
        try {
            Object obj = baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_VIDEO_KEY,() -> {
                List<Video> videoList = videoMapper.listVideo();
                System.out.println("从数据库里面找视频列表");
                return videoList;
            });

            if( obj instanceof List) {
                List<Video> videoList = (List<Video>) obj;
                return videoList;
            }
        }catch (Exception e) {

        }
        return null;
    }

    @Override
    public List<VideoBanner> listVideoBanner() {
//        List<VideoBanner> videoBanners = videoMapper.listVideoBanner();
//        System.out.println("从数据库里面找轮播图列表");
//        return videoBanners;

        try {
            Object obj = baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_BANNER_KEY, () ->{
                List<VideoBanner> videoBanners = videoMapper.listVideoBanner();
                System.out.println("从数据库里面找轮播图列表");
                return videoBanners;
            });

            if(obj instanceof List) {
                List<VideoBanner> videoBanners = (List<VideoBanner>) obj;
                return videoBanners;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Video findDetailById(int videoId) {
        //  单独构建一个缓存key，每个视频的key是不一样的
        String videoCacheKey = String.format(CacheKeyManager.VIDEO_DETAIL, videoId);
        try {
            Object cacheObject = baseCache.getOneHourCache().get(videoCacheKey, () -> {
                //  需要使用 mybatis 关联复杂查询
                Video video = videoMapper.findDetailById(videoId);
                System.out.println("从数据库中获取视频");
                return video;
            });
            if (cacheObject instanceof Video) {
                Video video = (Video) cacheObject;
                return video;
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Video findById(int videoId) {

        Video video = videoMapper.findById(videoId);

        return video;
    }


}
